import AudioPlayer from '@/views/homework/detail/question/english/audio-player'

const Mixin = {
  data() {
    return {
      audioPlayer: new AudioPlayer()
    }
  },
  mounted() {
    this.audioPlayer.init()
  },
  beforeDestroy() {
    this.audioPlayer.stop()
  },
  methods: {
    getScoreClass(proportion) {
      if (typeof proportion != 'number') return

      if (proportion >= 0 && proportion < 0.4) {
        return 'FF4040'
      } else if (proportion >= 0.4 && proportion < 0.8) {
        return 'F8AC23'
      } else {
        return '30C9A1'
      }
    },
    playAudio(el, url) {
      const onPlay = () => {
        const { currentSrc } = this.audioPlayer.context
        if (currentSrc != url) return

        el.className = 'playing'
      }

      const onPause = () => {
        const { currentSrc, currentTime } = this.audioPlayer.context
        if (currentSrc != url) return

        el.className = `pause ${currentTime}`
      }

      const onEnded = () => {
        const { currentSrc } = this.audioPlayer.context
        if (currentSrc != url) return

        el.className = ''
        this.audioPlayer.off('onPlay', onPlay)
        this.audioPlayer.off('onPause', onPause)
        this.audioPlayer.off('onEnded', onEnded)
      }

      const play = (currentTime) => {
        const audioCtx = this.audioPlayer.context
        this.audioPlayer.stop()
        if (!currentTime) {
          this.audioPlayer.on('onPlay', onPlay)
          this.audioPlayer.on('onPause', onPause)
          this.audioPlayer.on('onEnded', onEnded)
        }
        audioCtx.src = url
        audioCtx.currentTime = parseFloat(currentTime ? currentTime : 0)
        audioCtx.play()
      }

      if (el.className && el.className.indexOf('playing') != -1) {
        // 暂停
        this.audioPlayer.pause()
        return
      }

      if (el.className && el.className.indexOf('pause') != -1) {
        try {
          const [type, currentTime] = el.className.split(' ')
          // 恢复播放
          play(currentTime)
          return
        } catch (error) {}
      }

      // 播放新的音频
      play()
    }
  }
}

export default Mixin
